import wepy from 'wepy'
import { getLogger } from '../utils/util'
import tip from './tip'
import { APP_ID } from '../utils/constant'
const logger = getLogger()
function logInfo() {
  if (logger != null) {
    if (arguments == null || arguments.length == 0) {
    } else {
      var data = []
      for (var i = 0; i < arguments.length; i++) {
        data.push(arguments[i])
      }
      logger.info(data)
    }
  }
}
const wxRequest = async (params = {}, url, method='POST') => {
  console.log('wxRequest:', url, params)
  //  tip.loading();
  wx.showNavigationBarLoading()
  let data = params || {}
  var res = null
  var error = null
  var session = wx.getStorageSync('session')
  try {
    // data.sessionId = wx.getStorageSync('session');
    // data.encryptedData = wx.getStorageSync('encryptedData');
    // data.iv = wx.getStorageSync('encryptedData');
    console.log('wxRequest sessionId=', data.sessionId)
    res = await wepy.request({
      url: url,
      method: method,
      data: JSON.stringify(data),
      header: {
        // 'content-type': 'application/x-www-form-urlencoded',
        'Content-Type': 'application/json',
        appid: APP_ID,
        Authorization: 'Bearer ' + session
      }
    })
    console.log('wxRequest result: ', url, res)
  } catch (e) {
    console.log('wxRequest error:', e)
    error = e
    tip.error(e.errMsg)
  }
  logInfo({ url, request: data, respone: res, error, session })
  //  tip.loaded();
  wx.hideNavigationBarLoading()
  return res
}

module.exports = {
  wxRequest
}
